package cn.mesmile.flow.modules.processtask.service.impl;

import cn.hutool.core.util.StrUtil;
import cn.mesmile.flow.modules.processtask.model.dto.CompleteTaskDTO;
import cn.mesmile.flow.modules.processtask.model.vo.QueryTaskVO;
import cn.mesmile.flow.modules.processtask.service.ProcessTaskService;
import lombok.AllArgsConstructor;
import org.flowable.engine.*;
import org.flowable.task.api.Task;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @author zb
 * @date 2020/12/7 15:59
 * @Description
 */
@AllArgsConstructor
@Transactional(readOnly = true, propagation = Propagation.SUPPORTS,rollbackFor = Exception.class)
@Service
public class ProcessTaskServiceImpl implements ProcessTaskService {


    private final TaskService taskService;

    private final ManagementService managementService;

    private final RuntimeService runtimeService;

    private final DynamicBpmnService dynamicBpmnService;

    private final IdentityService identityService;

    @Override
    public List<QueryTaskVO> get() {
//        DelegateExecution execution
        // 加签
        Task task1 = taskService.newTask();



//        String sql = "SELECT ID_ FROM act_hi_taskinst  where ASSIGNEE_= '" + userCode + "' and DELETE_REASON_='completed' " +
//                " and END_TIME_ BETWEEN '" + DateUtil.formatDateTime(begin) + "' AND '" + DateUtil.formatDateTime(end) + "' and PROC_DEF_KEY_ in ( ";
//        Query nativeQuery = entityManager.createNativeQuery(sql);
//        List resultList = nativeQuery.getResultList();
//        int size = resultList == null ? 0 : resultList.size();

        /*
            【通过查询任务名的方式查询】
         */
        List<Task> tasks = taskService.createNativeTaskQuery()
                .sql("SELECT count(*) FROM " + managementService.getTableName(Task.class) +
                        " T WHERE T.NAME_ = #{taskName}")
                .parameter("taskName", "gonzoTask")
                .list();

        Map<String, String> properties = managementService.getProperties();

        // 查询候选组的任务
        List<Task> managersTask = taskService.createTaskQuery()
                .taskCandidateGroup("managers").list();
        System.out.println(">>>>>>>>>>>>>>>>>  managersTask："+ managersTask);

        List<Task> accountancy = taskService.createTaskQuery().taskCandidateGroup("accountancy").list();
        if (accountancy.size() >0) {
            Task task = accountancy.get(0);
            // 申领任务
            taskService.claim(task.getId(),"zhangsan");
        }
        // 查询审批人【查询待处理任务】
        List<Task> zhangsan = taskService.createTaskQuery().taskAssignee("zhangsan").list();

        List<Task> list = taskService.createTaskQuery().active().list();
        List<QueryTaskVO> queryTaskVOList = new ArrayList<>(list.size());
        for (Task task : list) {
            QueryTaskVO queryTaskVO = new QueryTaskVO(task);
            queryTaskVOList.add(queryTaskVO);
        }
        return queryTaskVOList;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void completeTask(CompleteTaskDTO completeTaskDTO) {

        /**
         *  申请领取任务
         */
        Task task = taskService.createTaskQuery()
                .taskId(completeTaskDTO.getTaskId()).singleResult();

        if ( StrUtil.isEmpty(task.getAssignee()) ) {
            taskService.claim(completeTaskDTO.getTaskId(),"张三");
        }

        // 设置完成任务的人和评论任务的人
        identityService.setAuthenticatedUserId("initiatorCode");

        //  ACT_HI_COMMENT  【评论表】  【event 认领任务】   【comment 评论】
        // 添加评论
        taskService.addComment(completeTaskDTO.getTaskId(),
                completeTaskDTO.getProcessInstanceId(),
                completeTaskDTO.getOpinion());

        taskService.complete(completeTaskDTO.getTaskId(),completeTaskDTO.getVariables());

    }
}
